# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
海拍客项目的接口,提供对外
# 文件：api_hpk
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import copy
import hashlib

import requests

from msydwork.config.config_hipac import w_url
from pycacho.cachobase.deal_json import dict_to_json
from pycacho.cachobase.deal_time import str_to_timestamp
from pycacho.cachobase.logger import Logger

logger = Logger("api_hpk").get_log()


class HpkApi():

    def __init__(self,merchantNo):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
            'content-Type': 'application/json'}
        self.partner_no = '20200106002647'
        self.partner_key = '3fda20b705aebf4aaf8097b309238ed8'
        self.merchantNo = merchantNo


    def apply_loan(self,loan_date, loanAmount,productNo,requestId):
        loan_info = {
            "feeRepayFrom": "1",
            "loanAmount": loanAmount,
            "loanDate": str(str_to_timestamp(loan_date)) + '000',
            "loanRemark": "zeng",
            "loanUse": "1",
            "merchantNo": self.merchantNo,
            "partnerNo": self.partner_no,
            "requestId": requestId,
            "queryUrl": ''
        }
        parm = ['feeRepayFrom', 'loanAmount', 'loanDate', 'loanRemark', 'loanUse', 'merchantNo', 'partnerNo',
                'requestId']
        fu_url = w_url + '/pay/applyLoan'
        data = copy.deepcopy(loan_info)
        info = self.web_sign(parm, loan_info)
        if productNo == 'P0001':
            loanPeriodType = 0
            loanPeriod = 30
        else:
            loanPeriodType = 1
            loanPeriod = 3
        data['productNo'] = productNo
        data['loanPeriod'] = loanPeriod
        data['loanPeriodType'] = loanPeriodType    # 借款期限类型，0-日，1-月，2-年
        data['password'] = self.merchantNo
        data['sign'] = info[1]
        data['queryUrl'] = info[0] + '&sign=' + info[1]
        req1 = requests.post(fu_url, json=data, headers=self.headers)
        data = req1.json()
        print("用信申请提交接口响应信息：")
        dict_to_json(data)


    # 内部接口加密
    def web_sign(self,parm,loan_info):
        info = []
        parm.sort()
        encrypt = ''
        for key in parm:
            encrypt = encrypt + key + '=' + loan_info[key]  + '&'
        encrypt = encrypt + 'key='+ self.partner_key
        print('加密组装的数据：',encrypt)
        info.append(encrypt)
        hl = hashlib.md5()
        hl.update(encrypt.encode(encoding='utf-8'))
        sign = hl.hexdigest()
        print('密钥：',sign)
        info.append(sign)
        return info

